//
//  StayHotelCtrl.m
//  Traveling
//
//  Created by Northwan on 15/6/4.
//  Copyright (c) 2015年 长沙市岳麓区立早网络科技有限公司. All rights reserved.
//  酒店列表

#import "StayHotelCtrl.h"
#import "StayHotelCell.h"
#import "HomeDataTool.h"
#import "HotelStayResult.h"
#import "HotelDetailCtrl.h"
#import "MsgDetailCtrl.h"


@interface StayHotelCtrl ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)NSMutableArray *itemArray;
@end

@implementation StayHotelCtrl

-(NSMutableArray *)itemArray{
    if (!_itemArray) {
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self.navigationItem setTitle:@"酒店列表"];
    [self initWithTableView];
    [self.tableView headerBeginRefreshing];
}
-(void)initWithTableView{
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefresh)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRefresh)];
}

-(void)headerRefresh{
    [self requestDataWithId:0];
}

-(void)footerRefresh{
    NSInteger maxId = 0;
    if(self.itemArray.count){
       HotelStayResult *result =  [self.itemArray lastObject];
       maxId =  result.id;
    }
    if(maxId>0){
        maxId--;
    }
    [self requestDataWithId:maxId];
}

-(void)requestDataWithId:(NSInteger)maxId{
  [HomeDataTool getHotelWithMaxId:maxId success:^(HotelStayRes *result) {
      if(result.isSucc){
          [Utils refreshComplete:self.tableView];
          if(maxId == 0){
              [self.itemArray removeAllObjects];
          }
          [self.itemArray addObjectsFromArray:result.datas];
          [self.tableView reloadData];
      }else{
          [DialogUtils showTips:result.msg];
      }
  } failure:^(NSError *error) {
      [Utils refreshComplete:self.tableView];
      [DialogUtils showTips:@"加载失败"];
  }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    StayHotelCell *cell = [StayHotelCell cellWithTableView:tableView];
    [cell initData:self.itemArray[indexPath.row]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return MSGCELLHEIGHT;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HotelDetailCtrl *ctrl = [[HotelDetailCtrl alloc] initWithHotelStayResult:self.itemArray[indexPath.row]];
    [self.navigationController pushViewController:ctrl animated:YES];
}

@end
